<template>
    <div class="market-layout">
        <el-container>
            <el-header height="60px">
                <div class="header-container">
                    <div class="logo">
                        <router-link to="/market">
                            <h1>拍卖市场</h1>
                        </router-link>
                    </div>
                    <div class="search-box">
                        <el-input v-model="searchKeyword" placeholder="搜索拍卖品" class="search-input"
                            @keyup.enter="handleSearch">
                            <template #append>
                                <el-button @click="handleSearch">
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </el-button>
                            </template>
                        </el-input>
                    </div>
                    <div class="user-actions">
                        <el-dropdown trigger="click">
                            <span class="user-menu-link">
                                欢迎，{{ userStore.name || '用户' }} <el-icon><arrow-down /></el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click="goToUserCenter">用户中心</el-dropdown-item>
                                    <el-dropdown-item @click="goToMyBids">我的竞拍</el-dropdown-item>
                                    <el-dropdown-item @click="goToMyOrders">我的订单</el-dropdown-item>
                                    <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </div>
            </el-header>

            <el-container>
                <el-aside width="220px">
                    <div class="category-nav">
                        <h3>拍卖品分类</h3>
                        <el-menu :default-active="activeCategory" class="category-menu" @select="handleCategorySelect">
                            <el-menu-item index="all">
                                <el-icon>
                                    <Menu />
                                </el-icon>
                                <span>全部分类</span>
                            </el-menu-item>

                            <el-sub-menu v-for="(type, index) in categoryTypes" :key="'type-' + index"
                                :index="'type-' + type.value">
                                <template #title>
                                    <el-icon>
                                        <FolderOpened />
                                    </el-icon>
                                    <span>{{ type.label }}</span>
                                </template>

                                <el-menu-item v-for="category in getCategoriesByType(type.value)" :key="category.id"
                                    :index="category.id.toString()">
                                    {{ category.name }}
                                </el-menu-item>
                            </el-sub-menu>
                        </el-menu>
                    </div>
                </el-aside>

                <el-main>
                    <router-view />
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watchEffect } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getUserCategoryList } from '@/api/category'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, Search, Menu, FolderOpened } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const searchKeyword = ref('')
const categories = ref([])
const activeCategory = ref('all')

// 用户相关路由导航
const goToUserCenter = () => {
    router.push('/user')
}

const goToMyBids = () => {
    router.push('/user/bids')
}

const goToMyOrders = () => {
    router.push('/user/orders')
}

// 退出登录
const handleLogout = () => {
    ElMessageBox.confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        userStore.logout()
        router.push('/login')
        ElMessage.success('退出登录成功')
    }).catch(() => { })
}

// 分类类型
const categoryTypes = [
    { value: 1, label: '电子数码' },
    { value: 2, label: '珠宝首饰' },
    { value: 3, label: '古董收藏' },
    { value: 4, label: '字画收藏' }
]

// 按类型获取分类
const getCategoriesByType = (type) => {
    return categories.value.filter(item => item.type === type)
}

// 搜索处理
const handleSearch = () => {
    router.push({
        path: '/market',
        query: {
            keyword: searchKeyword.value,
            category: activeCategory.value !== 'all' ? activeCategory.value : null
        }
    })
}

// 分类选择处理
const handleCategorySelect = (index) => {
    activeCategory.value = index
    // 如果是分类类型，不导航
    if (index.startsWith('type-')) return

    if (index === 'all') {
        router.push('/market')
    } else {
        console.log('跳转到分类页面，分类ID:', index)
        router.push(`/market/category/${index}`)
    }
}

// 获取所有分类
const fetchCategories = async () => {
    try {
        // 获取用户端分类列表
        const res = await getUserCategoryList()
        console.log('获取到所有分类数据:', res)
        if (res && Array.isArray(res)) {
            categories.value = res
        } else if (res && res.data && Array.isArray(res.data)) {
            categories.value = res.data
        } else if (res && res.code === 1 && res.data && Array.isArray(res.data)) {
            // 处理标准的Result<List>格式
            categories.value = res.data
            console.log('解析后的分类数据:', categories.value)
        }
    } catch (error) {
        console.error('获取分类失败:', error)
    }
}

// 更新活动分类
const updateActiveCategory = () => {
    const { path } = route
    if (path.includes('/category/')) {
        const categoryId = path.split('/').pop()
        activeCategory.value = categoryId
    } else {
        activeCategory.value = 'all'
    }
}

onMounted(() => {
    fetchCategories()
    updateActiveCategory()
})

// 监听路由变化，更新活动分类
watchEffect(() => {
    if (route.path) {
        updateActiveCategory()
    }
})
</script>

<style scoped>
.market-layout {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

.el-container {
    height: 100%;
}

.el-header {
    background-color: #409EFF;
    color: #fff;
    line-height: 60px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100%;
    padding: 0 20px;
}

.logo h1 {
    margin: 0;
    font-size: 24px;
    color: #fff;
}

.logo a {
    text-decoration: none;
    color: #fff;
}

.search-box {
    flex: 1;
    max-width: 500px;
    margin: 0 20px;
}

.search-input {
    width: 100%;
}

.user-actions {
    display: flex;
    align-items: center;
}

/* 用户菜单样式 */
.user-menu-link {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #fff;
    cursor: pointer;
    padding: 5px 10px;
    border-radius: 4px;
    transition: background-color 0.3s;
}

.user-menu-link:hover {
    background-color: rgba(255, 255, 255, 0.2);
}

.user-menu-link .el-icon {
    margin-left: 5px;
}

.el-aside {
    background-color: #f5f7fa;
    border-right: 1px solid #e6e6e6;
    padding: 20px 0;
}

.category-nav {
    padding: 0 10px;
}

.category-nav h3 {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    padding-left: 10px;
    color: #303133;
}

.category-menu {
    border-right: none;
}

.el-main {
    padding: 20px;
    background-color: #f5f7fa;
}
</style>